<link rel=stylesheet href='./style.css'>
<script src="./vue_2.6.14.js"></script>

<div id=root><div></div></div>

<script>

Vue.component('app-header', {
  template: `
    <div>
      <h1>vuejs@${Vue.version}</h1>
      <h3>Reading List: {{ bookCount }}</h3>
    </div>
  `,
  props: [ 'bookCount' ],
});

Vue.component('new-book', {
  data() {
    return {
      name: '',
    }
  },
  template: `
    <div>
      <input v-model='name' @keypress.enter='onNewBook'>
      <button @click='onNewBook'>new book</button>
    </div>
  `,
  emits: ['newbook'],
  methods: {
    onNewBook() {
      this.$emit('newbook', this.name);
    }
  },
});
Vue.component('book-item', {
  template: `
    <div>{{ name }}</div>
  `,
  props: ['name'],
});

Vue.component('book-list', {
  props: ['books'],
  template: `
    <ol>
      <li v-for='book in books' :key='book.name'>
        <book-item :name='book.name'></book-item>
      </li>
    </ol>
  `,
});

Vue.component('color-button', {
  props: {
    color: String,
    enabled: Boolean,
    nested: Object,
  },
  template: `
    <button :disabled='enabled' :class='color'>button {{nested.index}}</button>
  `,
});

Vue.component('button-grid', {
  render(createElement) {
    const buttons = [];
    for (let i = 0; i < 9; ++i) {
      buttons.push(createElement('color-button', {
        props: {
          color: ['red', 'green', 'blue'][i % 3],
          enabled: i % 2 === 0,
          nested: {
            index: i,
            value: i + 0.1,
          }
        }
      }, null));
    };
    return createElement('div', null, buttons);
  }
});

window.mountApp = element => new Vue({
  el: element,

  template: `
    <div>
      <app-header :bookCount='books.length'></app-header>
      <new-book @newbook='addNewBook'></new-book>
      <book-list :books='books'></book-list>
      <button-grid></button-grid>
      <div ref="mountPoint"></div>
    </div>
  `,

  data() {
    return {
      books: [
        {name: 'Pride and Prejudice' },
        {name: 'To Kill a Mockingbird' },
        {name: 'The Great Gatsby' },
      ],
    };
  },

  methods: {
    addNewBook(name) {
      console.log('here');
      this.books.push({name});
    }
  },
});
window.app = window.mountApp(document.querySelector('#root div'));
window.mountNestedApp = () => window.mountApp(window.app.$refs.mountPoint);

</script>
